package com.hurl.library.http;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

public class HttpRequest {
	private static final Logger log = Logger.getLogger(HttpRequest.class);
	
	HttpClient client;
	HttpOptions options;
	public HttpRequest(){
		this(null);
	}
	
	public HttpRequest(HttpOptions options){
		initClient(options);
	}
	
	private void initClient(HttpOptions options){
		client = new DefaultHttpClient();
		
		if(options==null){
			options = new HttpOptions();
		}
		this.options=options;
		
		client.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT,10*1000);
		if(options.getSocketTimeoutInMillis()<=0){
			client.getParams().removeParameter(HttpConnectionParams.SO_TIMEOUT);
		}else{
			client.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT,options.getSocketTimeoutInMillis());
		}
		client.getParams().setParameter(HttpProtocolParams.HTTP_CONTENT_CHARSET,options.getCharset());
	}
	public void requestImage(String url,File saveToFile)throws HttpException{
		HttpGet getMethod = new HttpGet(url);
		try{
			HttpResponse response = null;
			int retry = options.getRetry();
			while(true){
				try{
					log.debug("请求："+url);
					response = client.execute(getMethod);
					log.debug("响应码："+response.getStatusLine().getStatusCode());
					break;
				}catch(IOException ioe){
					log.error("请求出错："+ioe.getMessage());
					retry--;
					if(retry<=0){
						throw ioe;
					}
				}
			}
			int status = response.getStatusLine().getStatusCode();
			if(status==HttpStatus.SC_OK){
				HttpEntity entity = response.getEntity();
				FileOutputStream output = new FileOutputStream(saveToFile);
				output.write(EntityUtils.toByteArray(entity));
				
			}else{
				throw new HttpException(status,"请求失败，响应代码："+status);
			}
		}catch(IOException ioe){
			getMethod.abort();
			ioe.printStackTrace();
			log.error(ioe);
			throw new HttpException("请求失败："+ioe.getMessage(),ioe);
		}
	}
	public String request(String url) throws HttpException{
		HttpGet getMethod = new HttpGet(url);
		try{
			HttpResponse response = null;
			int retry = options.getRetry();
			while(true){
				try{
					log.debug("请求："+url);
					response = client.execute(getMethod);
					log.debug("响应码："+response.getStatusLine().getStatusCode());
					break;
				}catch(IOException ioe){
					log.error("请求出错："+ioe.getMessage());
					retry--;
					if(retry<=0){
						throw ioe;
					}
				}
			}
			int status = response.getStatusLine().getStatusCode();
			if(status==HttpStatus.SC_OK){
				HttpEntity entity = response.getEntity();
				String responseContent = EntityUtils.toString(entity);
				EntityUtils.consume(entity);
				return responseContent;
			}else{
				throw new HttpException(status,"请求失败，响应代码："+status);
			}
		}catch(IOException ioe){
			getMethod.abort();
			ioe.printStackTrace();
			log.error(ioe);
			throw new HttpException("请求失败："+ioe.getMessage(),ioe);
		}
	}
}
